package com.gdface.admin.gdface_attend;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.gdface.admin.gdface_attend.utils.DaoUtils;
import com.gdface.admin.gdface_attend.utils.DateUtils;
import com.gdface.admin.gdface_attend.utils.FileUtils;
import com.pefis.natives.Ast2600JNI;
import com.pefis.natives.PfsBioInfo;

import net.gdface.face.Entity.Att_user;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

public class EnrollActivity extends Activity implements Runnable {

    ImageView mEnrollFaceView;
    FaceDetectionView mFaceDetectionView;
    TextView mUserIDTxt;
    RatingBar mRatingBar;

    CheckBox mSwitchCamera;
    private boolean mColorCamera;
    private int mImageWidth;
    private int mImageHeight;
    private Thread mface_pro;
    public boolean m_bExitLoop = false;
    private byte[] mColorImageFrame;
    private byte[] mProcessImageFrame;
    public byte[] m_Template;
    private int mContextID;

    private boolean m_Enroll = false;

    private EditText et_ComID, et_Company;
    private Spinner sp_Job, sp_Per;
    private Button bt_Enroll_Start;
    private String info_comID, info_company;
    private int info_job, info_per;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add);
        mEnrollFaceView = (ImageView) this.findViewById(R.id.EnrollFaceView);
        mFaceDetectionView = (FaceDetectionView) this.findViewById(R.id.FaceDetectionView);
        mUserIDTxt = (TextView) this.findViewById(R.id.enroll_id);
        mRatingBar = (RatingBar) this.findViewById(R.id.ratingBar);

        mRatingBar.setNumStars(PfsBioInfo.getInstance().enroll_face_count[0]);
        mRatingBar.setMax(PfsBioInfo.getInstance().enroll_face_count[0]);
//        mUserIDTxt.setText(PfsBioInfo.getInstance().mEnrollID + "");
        PfsBioInfo.getInstance().mEnrollID = (int) DaoUtils.getMaxId();
        mUserIDTxt.setText(PfsBioInfo.getInstance().mEnrollID + "");
        mSwitchCamera = (CheckBox) this.findViewById(R.id.switch_camera);

        mImageWidth = PfsBioInfo.getInstance().face_img_w[0];
        mImageHeight = PfsBioInfo.getInstance().face_img_h[0];
        mColorImageFrame = new byte[mImageWidth * mImageHeight];
        mProcessImageFrame = new byte[mImageWidth * mImageHeight];
        m_Template = new byte[PfsBioInfo.getInstance().enroll_template_size[0]];
        mface_pro = new Thread(this);
        m_bExitLoop = true;

        mSwitchCamera.setOnCheckedChangeListener(mCheckedChangeListener);
        mColorCamera = true;
        mContextID = PfsBioInfo.getInstance().mContextID;
        mface_pro.start();

        et_ComID = (EditText) findViewById(R.id.add_edit_company_id);
        et_Company = (EditText) findViewById(R.id.add_edit_company);
        sp_Job = (Spinner) findViewById(R.id.add_spinner_isonjob);
        sp_Per = (Spinner) findViewById(R.id.add_spinner_permission);
        bt_Enroll_Start = (Button) findViewById(R.id.add_bt_start_enroll);

        bt_Enroll_Start.setOnClickListener(clickListener);
    }

    View.OnClickListener clickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.add_bt_start_enroll:
                    checkUserContext();
                    break;
            }
        }
    };

    private String comid;

    private void checkUserContext() {
        comid = "";
        comid = et_ComID.getText().toString().trim();
        String company = et_Company.getText().toString().trim();
        if (null == comid || 0 == comid.length() || comid.equals("")) {
            Toast.makeText(this, "工号不能为空，请输入工号!", Toast.LENGTH_SHORT).show();
            bt_Enroll_Start.setEnabled(true);
            bt_Enroll_Start.setTextColor(this.getResources().getColor(R.color.TextColorBlack));

            m_Enroll = false;
        } else {
            Toast.makeText(this, "信息确认，请正对摄像头开始人脸注册!", Toast.LENGTH_SHORT).show();
            bt_Enroll_Start.setEnabled(false);
            bt_Enroll_Start.setTextColor(this.getResources().getColor(R.color.TextColorGray));
            m_Enroll = true;

            info_comID = comid;
            info_company = company;
            info_job = sp_Job.getSelectedItemPosition();
            info_per = sp_Per.getSelectedItemPosition();
        }
    }

    private OnCheckedChangeListener mCheckedChangeListener = new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

            mColorCamera = !mColorCamera;
        }
    };
    Handler mImageDraw = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            mEnrollFaceView.setImageBitmap((Bitmap) msg.obj);
        }
    };

    @Override
    public void onBackPressed() {

        finish();
        m_bExitLoop = false;
        PfsBioInfo.getInstance().killMediaPlayer();

    }

    @Override
    public void onDestroy() {
        // Don't forget to shutdown!
        PfsBioInfo.getInstance().killMediaPlayer();

        super.onDestroy();
    }

    public void DrawFaceImage(byte[] rawData, Boolean IsSave) {

        if (mColorCamera)
            PfsBioInfo.getInstance().CreateColorBitmapFromBayer(rawData);
        else
            PfsBioInfo.getInstance().CreateGrayBitmapFromBayer(rawData);

        mImageDraw.obtainMessage(0, PfsBioInfo.getInstance().m_bmp).sendToTarget();
    }


    Handler mShowCount = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            mRatingBar.setProgress(msg.what);
        }
    };


    Handler mShowResult = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            PfsBioInfo.getInstance().mMessageKind = msg.what;
            PfsBioInfo.getInstance().mShowMessageFlag = true;

        }
    };

    Handler mClose = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0x81:
                    int id = (int) msg.obj;
                    FileUtils.deleteAllInDir(dir_enroll);
                    Toast.makeText(EnrollActivity.this, "用户重复建模，id为 " + id, Toast.LENGTH_SHORT).show();
                    break;
                case 0x82:
                    String vn = String.valueOf(msg.obj);
                    Toast.makeText(EnrollActivity.this, "設置模型出错!   "+vn, Toast.LENGTH_SHORT).show();
                    break;
                case 0x83:
                    Toast.makeText(EnrollActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
                    break;
            }

            int i = 0;
            try {
                while (i < 3) {
                    Thread.sleep(100);
                    i++;
                }
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();

            }
            onBackPressed();
        }
    };


    @Override
    public void run() {
        // TODO Auto-generated method stub
        int vnRet;
        int enroll_seq = 0;
        int[] dup_id = new int[1];
        Ast2600JNI.getInstance().pisFcInfraredLedControl(mContextID, PfsBioInfo.PFSBIO_IR_LED_HIGH_ON);
        short[] faceRect = new short[8];
        while (m_bExitLoop) {
            //int vRet =
            if (mColorCamera) {
                Ast2600JNI.getInstance().pisFcColorImageCapture(PfsBioInfo.getInstance().mContextID, mColorImageFrame);
                Ast2600JNI.getInstance().pisFcGrayImageCapture(PfsBioInfo.getInstance().mContextID, mProcessImageFrame);
                DrawFaceImage(mColorImageFrame, true);
            } else {
                Ast2600JNI.getInstance().pisFcGrayImageCapture(PfsBioInfo.getInstance().mContextID, mProcessImageFrame);
                DrawFaceImage(mProcessImageFrame, true);
            }

			/*Ast2600JNI.getInstance().pisFcColorImageCapture(PfsBioInfo.getInstance().mContextID,mColorImageFrame );
            DrawFaceImage(mColorImageFrame,true);
			PfsBioInfo.getInstance().ConvertBayerToGray(mColorImageFrame, mProcessImageFrame, mImageWidth, mImageHeight);
			*/

            vnRet = Ast2600JNI.getInstance().pisFcCheck(mContextID, mProcessImageFrame, mImageWidth, mImageHeight, faceRect);

            if (vnRet != PfsBioInfo.PFSBIO_OK) {
                Ast2600JNI.getInstance().pisLedControl(mContextID, PfsBioInfo.PFSBIO_OKNOLED, PfsBioInfo.PFSBIO_LED_OFF);

                mFaceDetectionView.setRect(-10, -10, -10, -10);
                mFaceDetectionView.postInvalidate();
                continue;
            }

            mFaceDetectionView.setRect(faceRect[0], faceRect[2], faceRect[1] - faceRect[0], faceRect[3] - faceRect[2]);
            mFaceDetectionView.postInvalidate();

            if (m_Enroll) {
                vnRet = Ast2600JNI.getInstance().pisFcEnroll(mContextID, enroll_seq, mProcessImageFrame, mImageWidth, mImageHeight, m_Template);

                if (vnRet != PfsBioInfo.PFSBIO_OK) continue;

                enroll_seq++;

                if (PfsBioInfo.isSaveImg)
                    saveGRAYImageData(mProcessImageFrame, enroll_seq);
                mShowCount.sendEmptyMessage(enroll_seq);
                try {
                    PfsBioInfo.getInstance().playAudio(PfsBioInfo.AUDIO_DING);
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                if (enroll_seq >= PfsBioInfo.getInstance().enroll_face_count[0])
                    break;
            } else {

            }
        }

        Ast2600JNI.getInstance().pisFcInfraredLedControl(mContextID, PfsBioInfo.PFSBIO_IR_LED_LOW_ON);

        //检测重复建模
        vnRet = Ast2600JNI.getInstance().pisFcCheckDuplicate(mContextID, m_Template, dup_id);
        if (dup_id[0] != PfsBioInfo.getInstance().mEnrollID)
            if (vnRet != PfsBioInfo.PFSBIO_OK) {
                mShowResult.sendEmptyMessage(PfsBioInfo.PFSBIO_ERR_DOUBLE_CHECK);
//                mClose.sendEmptyMessage(0x81);
                mClose.obtainMessage(0x81, dup_id[0]).sendToTarget();
                return;
            }

        //设置模型数据
        vnRet = Ast2600JNI.getInstance().pisFcSetAtTptArray(mContextID, PfsBioInfo.getInstance().mEnrollID, m_Template);
        if (vnRet != 0) {
            mShowResult.sendEmptyMessage(PfsBioInfo.PFSBIO_ERR_ENROLL_COUNT_OVER);
//            mClose.sendEmptyMessage(0x82);
            mClose.obtainMessage(0x82,vnRet).sendToTarget();
            return;
        }

        try {
            PfsBioInfo.getInstance().playAudio(PfsBioInfo.AUDIO_OK);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            Thread.sleep(800);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Att_user user = new Att_user(Long.valueOf(PfsBioInfo.getInstance().mEnrollID), info_company, info_comID, info_job, DateUtils.getNowDate(), info_per);
        Log.i("hwwlog", " insertUser = " + user.toString());
        DaoUtils.insertUser(user);

        PfsBioInfo.getInstance().WriteByteToFile(m_Template, PfsBioInfo.TEMPLATE_DB_PATH + PfsBioInfo.getInstance().mEnrollID);
//        PfsBioInfo.getInstance().SaveUserPhotoFile(PfsBioInfo.PHOTO_DB_PATH + PfsBioInfo.getInstance().mEnrollID + ".jpeg");
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        PfsBioInfo.getInstance().m_bmp.compress(Bitmap.CompressFormat.JPEG, 50, outputStream);
        saveImageData(PfsBioInfo.PHOTO_DB_PATH, PfsBioInfo.getInstance().mEnrollID, outputStream.toByteArray());

        mShowResult.sendEmptyMessage(PfsBioInfo.PFSBIO_OK);
        mClose.sendEmptyMessage(0x83);
    }


    private void saveImageData(String dir, int id, byte[] data) {

        File filename = new File(dir);
        if (!filename.exists()) {
            filename.mkdir();
        }

        String name = id + ".JPEG";

        filename = new File(dir, name);

        if (filename.exists()) {
            filename.delete();
        }

        try {
            filename.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            FileOutputStream out = new FileOutputStream(filename);
            out.write(data);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.i("hwwlog", "保存" + dir + "     " + name + "sccess");
    }

    private String dir_enroll;
    private String dir_Base = PfsBioInfo.INIT_DATA_PATH + "/Enroll/";

    private void saveGRAYImageData(byte[] data_gray, int sum) {


        int i;
        for (int j = 0; j < PfsBioInfo.getInstance().face_img_h[0]; j++)
            for (int k = 0; k < PfsBioInfo.getInstance().face_img_w[0]; k++) {
                i = j * PfsBioInfo.getInstance().face_img_w[0] + k;
                iden_byte[i * 4] = iden_byte[i * 4 + 1] = iden_byte[i * 4 + 2] = data_gray[i]; //Invert the source bits
                iden_byte[i * 4 + 3] = -1; //0xff, that's the alpha.
            }
        iden_bmp.copyPixelsFromBuffer(ByteBuffer.wrap(iden_byte));

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        iden_bmp.compress(Bitmap.CompressFormat.JPEG, 50, outputStream);

        File fileenroll = new File(dir_Base);
        if (!fileenroll.exists()) {
            fileenroll.mkdir();
        }

        dir_enroll = dir_Base + comid + "/";
        File filename = new File(dir_enroll);
        if (!filename.exists()) {
            filename.mkdir();
        }

        String name = sum + ".JPEG";

        filename = new File(dir_enroll, name);

        if (filename.exists()) {
            filename.delete();
        }

        try {
            filename.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            FileOutputStream out = new FileOutputStream(filename);
            out.write(outputStream.toByteArray());
            out.flush();
            out.close();
            Log.i("hwwlog", " saveGRAYImageData" + dir_enroll + "     " + name + "");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public byte[] iden_byte = new byte[PfsBioInfo.getInstance().face_img_h[0] * PfsBioInfo.getInstance().face_img_w[0] * 4];
    private Bitmap iden_bmp = Bitmap.createBitmap(PfsBioInfo.getInstance().face_img_w[0], PfsBioInfo.getInstance().face_img_h[0], Bitmap.Config.ARGB_8888);


}
 